package com.chen.service.impl;

import com.chen.NotFoundException;
import com.chen.dao.BlogDao;
import com.chen.pojo.Blog;
import com.chen.service.BlogService;
import com.chen.utils.MarkdownUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    BlogDao blogDao;

    @Override
    public Blog getBlog(Long id) {
        return blogDao.getBlog(id);
    }

    @Override
    public List<Blog> listBlog() {
        return blogDao.listBlog();
    }

    @Override
    public Blog getAndConvert(Long id) {
        Blog blog = blogDao.getAndConvert(id);
        Blog b = new Blog();

        BeanUtils.copyProperties(blog, b);
        String content = b.getContent();
        b.setContent(MarkdownUtils.markdownToHtmlExtensions(content));

        return b;
    }

    @Override
    public int saveBlog(Blog blog) {
        if (blog.getId() == null) {
            blog.setCreateTime(new Date());
            blog.setUpdateTime(new Date());
            blog.setViews(0);
        }
        return blogDao.saveBlog(blog);
    }

    @Override
    public int updateBlog(Long id, Blog blog) {
        int i = blogDao.updateBlog(id, blog);
        if (i == 0) {
            throw new NotFoundException("该博客不存在");
        }
        return i;
    }

    @Override
    public int deleteBlog(Long id) {
        return blogDao.deleteBlog(id);
    }
}
